﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Surf.GrpcInvoker.Demo.Core
{
    /// <summary>信息处理器  消息/参数序列化和反序列化的封装</summary>
    public class Marshaller<T>
    {
        readonly Func<T, byte[]> _serializer;
        readonly Func<byte[], T> _deserializer;

        public Marshaller(Func<T, byte[]> serializer, Func<byte[], T> deserializer)
        {
            _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
            _deserializer = deserializer ?? throw new ArgumentNullException(nameof(deserializer));
        }

        public Func<T, byte[]> Serializer
        {
            get { return _serializer; }
        }

        public Func<byte[], T> Deserializer
        {
            get { return _deserializer; }
        }
    }

    /// <summary>信息处理器的 创建器</summary>
    public static class Marshallers
    {
        public static Marshaller<T> Create<T>(Func<T, byte[]> serializer, Func<byte[], T> deserializer)
        {
            return new Marshaller<T>(serializer, deserializer);
        }

        /// <summary>创建 字符串 类型的消息处理器</summary>
        public static Marshaller<string> StringMarshaller
        {
            get
            {
                return new Marshaller<string>(System.Text.Encoding.UTF8.GetBytes, System.Text.Encoding.UTF8.GetString);
            }
        }
    }
}
